package com.wzq.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzq.constant.SystemConstant;
import com.wzq.controller.admin.GetSome;
import com.wzq.dao.dto.WinnerLikeDto;
import com.wzq.dao.pojo.*;
import com.wzq.properties.WeixinProperties;
import com.wzq.service.IWechat_userService;
import com.wzq.util.HttpClientUtil;
import com.wzq.util.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author pzm
 * @since 2022-08-31
 */
@RestController
    @RequestMapping("/wechat_user")
public class Wechat_userController extends GetSome {


    @Autowired
    private WeixinProperties weixinProperties;

    @Autowired
    private HttpClientUtil httpClientUtil;

    @Autowired
    private IWechat_userService iWechat_userService;


    /**
     * 微信用户登录
     * @return
     * @param wechat_user
     */
    @RequestMapping("/wxlogin")
    public R wxLogin(@RequestBody Wechat_user wechat_user){
        String jscode2sessionUrl=weixinProperties.getJscode2sessionUrl()+"?appid="+weixinProperties.getAppid()+"&secret="+weixinProperties.getSecret()+"&js_code="+ wechat_user.getCode()+"&grant_type=authorization_code";
        String result = httpClientUtil.sendHttpGet(jscode2sessionUrl);
        JSONObject jsonObject= JSON.parseObject(result);
        String openid = jsonObject.get("openid").toString();
        // 插入用户到数据库  假如说 用户不存在 我们插入用户  如果用户存在 我们更新用户
        Wechat_user resultWxUserInfo = iWechat_userService.getOne(new QueryWrapper<Wechat_user>().eq("openid", openid));
        if(resultWxUserInfo==null){
            System.out.println("不存在 插入用户");
            wechat_user.setOpenid(openid);
            iWechat_userService.save(wechat_user);
            // 添加 t_timeselect
            TimeSelection timeSelection = new TimeSelection();
            timeSelection.setW_id(wechat_user.getId());
            iTimeSelectionService.save(timeSelection);
        }else{
            System.out.println("存在 更新用户");
            resultWxUserInfo.setSys_number(wechat_user.getSys_number());
            resultWxUserInfo.setNickName(wechat_user.getNickName());
            resultWxUserInfo.setPhone(wechat_user.getPhone());
            resultWxUserInfo.setAvatarUrl(wechat_user.getAvatarUrl());
            iWechat_userService.updateById(resultWxUserInfo);
        }
        Wechat_user openid1 = iWechat_userService.getOne(new QueryWrapper<Wechat_user>().eq("openid", openid));
        Integer id = openid1.getId();
        // 利用jwt生成token返回到前端
        String token = JwtUtils.createJWT(openid, wechat_user.getNickName(), SystemConstant.JWT_TTL);
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("id" , id);
        return R.ok(resultMap);
    }

    //   修改id对应微信用户
    @PutMapping("/update")
    public Result updateById(@RequestBody Wechat_user user) {
//        if (user.getSex()==0) {
//            user.setSex(iWechat_userService.getById(user.getId()).getSex());
//        }
        boolean flag = iWechat_userService.updateById(user);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag);
    }


    //   修改id对应微信用户
    @PutMapping
    public Result update(@RequestBody Wechat_user user) {
        Wechat_user SelectUserId = iWechat_userService.getById(user.getId());
        System.out.println(SelectUserId);
        if (SelectUserId.getUsername() != null || SelectUserId.getPassword() != null ){
            return new Result(Code.UPDATE_ERR,false,"已被绑定");
        }
        boolean flag = iWechat_userService.updateById(user);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }

    //   修改id对应微信用户的性别
    @PostMapping("/updateSexById")
    public Result updateSexById(@RequestBody Wechat_user user) {
        boolean flag = iWechat_userService.updateById(user);
        return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
    }


    //    根据id解绑微信用户
    @DeleteMapping("/unbind")
    public Result deleteById(@RequestBody Wechat_user user) {
        boolean flag =  iWechat_userService.removeById(user.getId());
        return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
    }

    //    获得id对应用户信息
    @GetMapping("/auto/{id}")
    public Result getById(@PathVariable Integer id) {
        Wechat_user user = iWechat_userService.getById(id);
        if(user.getUsername()==null){
            System.out.println("不存在 插入用户");
            return new Result(Code.GET_ERR,user.getUsername(),"不存在,请先注册！");
        }
        Map<String , Wechat_user> map = new HashMap<>();
        map.put("data", user);
        return new Result(Code.GET_OK,map,"登陆成功！");
    }

    //获得所有用户信息
    @GetMapping
    public Result getAll() {
        List<Wechat_user> list = iWechat_userService.list();
        System.out.println(list);
        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
        String msg = list != null ? "" : "数据查询失败，请重试！";
        return new Result(code,list,msg);
    }

    //获得所有用户信息(排除自己)
    @GetMapping("getAllNotMe")
    public Result getAllNotMe(Integer id) {
        List<Wechat_user> list = iWechat_userService.getAllNotMe(id);
        System.out.println(list);
        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
        String msg = list != null ? "" : "数据查询失败，请重试！";
        return new Result(code,list,msg);
    }

    //  邀请成员
    @GetMapping("/invite")
    public Result getinvite(@RequestBody Integer[] ids) {
        LambdaQueryWrapper<Wechat_user> lqw = new LambdaQueryWrapper<>();
        if (ids!=null)  lqw.notIn(Wechat_user::getId,ids);      //排除属于这个集合的行

        List<Wechat_user> list = iWechat_userService.list(lqw);
        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
        String msg = list != null ? "" : "数据查询失败，请重试！";
        return new Result(code,list,msg);
    }
//    //  成果专属
//    @PostMapping("/winner")
//    public Result getwinner(@RequestBody List<String> ids) {
//        LambdaQueryWrapper<Wechat_user> lqw = new LambdaQueryWrapper<>();
//        if (ids!=null)  lqw.in(Wechat_user::getId,ids);      //排除属于这个集合的行
//        List<Wechat_user> list = iWechat_userService.list(lqw);
//        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
//        String msg = list != null ? "" : "数据查询失败，请重试！";
//        return new Result(code,list,msg);
//    }

    //  邀请成员热搜索
    @PostMapping("/winnerlike")
    public Result getWinnerLike(@RequestBody WinnerLikeDto winnerLikeDto) {
        LambdaQueryWrapper<Wechat_user> lqw = new LambdaQueryWrapper<>();
        if (winnerLikeDto.getIds().size()>0) {
            lqw.in(Wechat_user::getId,winnerLikeDto.getIds());
            lqw.like(Wechat_user::getUsername,winnerLikeDto.getUsername());
        }
        List<Wechat_user> list = iWechat_userService.list(lqw);
        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
        String msg = list != null ? "" : "数据查询失败，请重试！";
        return new Result(code,list,msg);
    }

//    姓名热搜索
    @PostMapping("/like")
    public Result getNameLike(@RequestBody String name){
        LambdaQueryWrapper<Wechat_user> lqw = new LambdaQueryWrapper<>();
        lqw.select(Wechat_user::getUsername,Wechat_user::getId);
        lqw.likeRight(name!=null && "".equals(name.trim()) , Wechat_user::getUsername,name);
        List<Wechat_user> list = iWechat_userService.list(lqw);
        Integer code = list != null ? Code.GET_OK : Code.GET_ERR;
        String msg = list != null ? "" : "数据查询失败，请重试！";
        return new Result(code,list,msg);
    }

    // 搜索功能：按名字条件查询所有成员（模糊查询）
    @GetMapping("/getMemberByUserName")
    public Result getMemberByUserName(@RequestParam("username") String username){
        List<Wechat_user> projectList = iWechat_userService.getMemberByUserName(username);
        System.out.println(projectList);
        if (projectList.isEmpty()){
            return new Result(Code.GET_ERR,"暂无搜索结果");
        }
        return new Result(projectList!= null ? Code.GET_OK: Code.GET_ERR,projectList);
    }


}

